<template>
  <base-breadcrumb>
    <!-- 搜索 -->
    <searchData
      :search-data="searchOption"
      :custom-reset="customReset"
      @search="search"
      @loadMonth="loadMonth"
    />
    <!-- 搜索 -->
    <a-card>
      <a-button
        v-btnPermission="'pm_068_exp_04'"
        type="primary"
        class="export-btn"
        :loading="exporting"
        @click="exportList"
      >导出全部</a-button>
      <div class="pub-table-select-count">
        <a-icon
          type="info-circle"
          theme="twoTone"
        />
        <span style="margin-right: 12px">
          总共：<span class="totalNum">{{ count }}</span>
        </span>
      </div>
      <s-table
        ref="table"
        row-key="id"
        :columns="columnsIndex"
        :data="loadData"
        show-size-changer
        show-quick-jumper
        :scroll="{ x: 2020, y: 440 }"
        :show-pagination="false"
        :children-column-name="'child'"
        :expanded-row-keys="expandedRowKeys"
        @expand="expandedRowsChange"
      >
        <template
          slot="auditStatus"
          slot-scope="text,record"
        >
          <a-badge
            v-if="record.code === 'PD'"
            :status="text | statusTypeFilter"
            :text="text | statusFilter"
          />
        </template>
        <template
          slot="rate"
          slot-scope="text"
        >
          <a-progress
            stroke-linecap="round"
            :percent="+text"
            status="active"
          >
            <template #format="text">
              <span>{{ text }}%</span>
            </template>
          </a-progress>
        </template>
        <template
          slot="operation"
          slot-scope="text, record"
        >
          <MoreButton>
            <a
              v-if="record.code == 'PD'"
              v-btnPermission="'pm_068_loo_01'"
              @click="handleDetail(record)"
            >查看</a>
            <a
              v-if="record.code == 'PD'"
              v-btnPermission="'pm_068_exp_05'"
              @click="handleExport(record)"
            >导出</a>
            <a
              v-if="record.code == 'PD' && (record.auditStatus== '0' || record.auditStatus=='3') && record.thisMonth"
              v-btnPermission="'pm_068_edi_02'"
              @click="handleUpdate(record)"
            >编辑</a>
            <a
              v-if="record.code == 'PD' && ( record.auditStatus== '2' || record.auditStatus=='4')"
              v-btnPermission="'pm_068_imp_03'"
              @click="handleImplementationManagement(record)"
            >实施管理</a>
            <a
              v-if="record.code == 'PD' && record.auditStatus!='0'"
              @click="$bus.$emit('showApprovalDetailsDialog', record.id)"
            >审批信息</a>
          </MoreButton>
        </template>
      </s-table>
    </a-card>
    <!-- 导出 -->
    <PlanExport
      :visible.sync="visible"
      :typeList="['excel']"
      :downloadFun="downloadFun"
    />
  </base-breadcrumb>
  
</template>
<script>
import { searchOption, columnsIndex, statusMap } from './model'
import weekPlanApi from '@/api/construction/weekPlanApi'
import monthPlanApi from '@/api/construction/monthPlanApi'
import PlanExport from '@/views/construction/components/PlanExport'
export default {
  name: 'weekPlan' + Date.now(),
  components: {
    PlanExport
  },
  filters: {
    // 状态过滤
    statusFilter(type) {
      const key = type.toString()
      return statusMap[key] && statusMap[key].text
    },
    statusTypeFilter(type) {
      const key = type.toString()
      return statusMap[key] && statusMap[key].status
    }
  },
  data() {
    return {
      // 查询参数
      searchData: {},
      // 搜索选项
      searchOption,
      // 表头
      columnsIndex,
      // 统计
      count: 0,
      // 默认展开项
      expandedRowKeys: [],
      // 导出时传入接口
      downloadFun: {},
      // 所属月默认值
      belongMonth: '',
      exporting: false,
      visible: false,
    }
  },
  mounted() {
    this.getWbsTemplateList()
  },
  methods: {
    /**
     * @description: 获取项目业态
     * @param {void}
     * @return {void}
     */
    getWbsTemplateList() {
      weekPlanApi.wbstemplate({ pageNo: 1, pageSize: 2000 }).then((res) => {
        this.searchOption[1].data = res.data.map((item) => {
          return {
            label: item.formatName,
            value: item.formatName
          }
        })
      })
    },
    /**
     * @description: 表格数据加载方法
     * @param {Object} parameter 分页信息
     * @return {Promise} 接口Promise
     */
    async loadData(parameter) {
      try {
        if ((this.searchData?.belongMonth ?? '') === '') {
          return Promise.resolve({
            data: []
          })
        }
        const res = await monthPlanApi.getMonthTree({
          ...this.searchData,
        })
        if (res && res.code === 200 && res.data && res.data.name && res.data.name !== '') {
          this.count = res.data.count || 0
          this.expandedRowKeys = res.expandedRowKeys || []
          return Promise.resolve({
            data: res.data ? [res.data] : []
          })
        } else {
          this.count = 0
          this.expandedRowKeys = []
          this.count = 0
          return Promise.resolve({
            data: []
          })
        }
        
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      }
    },
    /**
     * @description: 搜索
     * @param {Object} value 搜索数据
     * @return {Void}
     */
    search(value) {
      this.searchData = value || {}
      if ((this.searchData?.belongMonth ?? '') === '') {
        this.$message.warning('缺少所属月')
      }
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 所属月首次加载完成且有默认值回调
     * @param {string} val 默认值
     * @return {void}
     */
     loadMonth(val) {
      this.searchData = {
        ...this.searchData,
        belongMonth: val
      }
      this.belongMonth = val
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 手动展开
     * @param {boolean} expanded 是否展开
     * @param {object} record 行
     * @return {void}
     */
    expandedRowsChange(expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id)
      } else {
        this.expandedRowKeys.splice(
          this.expandedRowKeys.findIndex((el) => el === record.id),
          1
        )
      }
    },
    /**
     * @description: 查看
     * @param {object} record 行数据
     * @return {void}
     */
    handleDetail(record) {
      this.$router.push({
        path: '/construction/monthPlan/monthPlanView',
        query: {
          pageType: 'detail',
          rootId: record.id,
          projectName: record.name,
          projectId: record.projectId
        }
      })
    },
    /**
     * @description: 编辑
     * @param {object} record 行数据
     * @return {void}
     */
    handleUpdate(record) {
      this.$router.push({
        path: '/construction/monthPlan/monthPlanView',
        query: {
          pageType: 'update',
          rootId: record.id,
          projectName: record.name,
          projectId: record.projectId
        }
      })
    },
    /**
     * @description: 实施管理
     * @param {object} record 行数据
     * @return {void}
     */
    handleImplementationManagement(record) {
      this.$router.push({
        path: '/construction/monthPlan/implementationManagement',
        query: {
          rootId: record.id,
          projectName: record.name,
          projectId: record.projectId,
          passTime: record.passTime,
          belongMonth: record.belongMonth,
        }
      })
    },
    /**
     * @description: 自定义重置
     * @param {object} form 表单对象
     * @return {void}
     */    
    customReset(form){
      form.setFieldsValue({'belongMonth': this.belongMonth})
    },
    /**
     * @description: 导出全部
     * @return {void}
     */
     async exportList() {
      try {
        this.exporting = true
        this.handleDownload(await monthPlanApi.monthExclAll(this.searchData))
      } catch (error) {
        console.log(error)
      } finally {
        setTimeout(() => {
          this.exporting = false
        }, 200)
      }
    },
    /**
     * @description: 下载
     * @return {void}
     */
     handleDownload(res) {
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
    /**
     * @description: 导出
     * @param {object} record 行
     * @return {void}
     */
     handleExport(record) {
      this.visible = true
      // 导出接口
      this.downloadFun = {
        project: () => {
          return monthPlanApi.monthExcl(record.id)
        },
        excel: () => {
          return monthPlanApi.monthExcl(record.id)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.export-btn {
  margin-bottom: 10px;
}
</style>
